<template>
	<view class="house" :style="{ direction: $store.state.dir }">
		<view class="house-navbar">
			<status-bar></status-bar>
			<view class="house-navbar-tool">
				<flat-icon name="icon-back" @action="handleBack"></flat-icon>
				<view class="flex-layout-row">
					<favorite :likeId="house.likeId" :checked="house.hasLike" :houseId="house.id"></favorite>
					<flat-icon v-if="$isAgent" class="gap-row-left" name="icon-more" @action="handleAction"></flat-icon>
				</view>
			</view>
		</view>
		<view class="house-images">
			<u-swiper radius="0" :height="swipeHeight" :autoplay="false"
				:list="house.photoUrls ? house.photoUrls.split(',') : []" indicator indicatorMode="line"></u-swiper>
		</view>
		<view class="house-content">
			<view class="house-name section-title">{{ house.title }}</view>
			<view class="row between">
				<price v-if="type==1" :typeName="$t('text.rent')" :value="house.rentPrice" company="Monthly"></price>
				<price v-if="type==2" :typeName="$t('text.house.sell')" :value="house.secondPrice" company=""></price>
				<price v-if="type==3" :typeName="$t('text.new.selling')" :value="house.newPrice" company=""></price>
				<price v-if="type==4" :typeName="$t('text.hotel')" :value="house.familyPrice" company="Daliy"></price>
				<span class="tags" v-if="house.furnished==1">{{$t('text.furnished')}}</span>
				<span class="tags" v-if="house.furnished==0">{{ $t('text.unfurnished') }}</span>
			</view>
			<view class="gap-col-top" style="display: flex">
				<house-tag :value="house.propertyType"></house-tag>
			</view>
			<p v-if="type==1">{{$t('rent.prompt')}}</p>

			<view class="house-property">
				<view class="property-card shadow">
					<iconfont size="20px" name="icon-area"></iconfont>
					<text class="property-card-value">{{ house.area }}{{ ' sqm' }}</text>
				</view>
				<view class="property-card shadow">
					<iconfont size="20px" name="icon-bedroom"></iconfont>
					<text class="property-card-value">{{ house.roomNum }}</text>
				</view>
				<view class="property-card shadow">
					<iconfont size="20px" name="icon-bathroom"></iconfont>
					<text class="property-card-value">{{ house.toiletNum }}</text>
				</view>
			</view>
			<view class="section-title">{{ $t('detail.location') }}</view>
			<view class="house-agent shadow gap-col2">
				<location :address="house.address" :city="house.cityId" :mapname="house.mapname"
					:latitude="house.latitude" :longitude="house.longitude"></location>
			</view>
			<view class="house_time bg-white" v-if="type==4">
				<view class="time_top" @click.stop="onCalendar">
					<view class="time_text">
						<p>{{start_time}}</p>
						<span>{{ $t('check.in') }}</span>
					</view>
					<view class="time_night">
						{{nights}}{{ $t('text.nights') }}
					</view>
					<view class="time_text">
						<p>{{end_time}}</p>
						<span>{{ $t('check.out') }}</span>
					</view>
				</view>
				<view class="time_bottom">
					<ul>
						<li>
							<image src="@/static/time_01.png" mode=""></image>
							<p>need pay</p>
							<span>{{actual_money}}</span>
						</li>
						<li>
							<image src="@/static/time_02.png" mode=""></image>
							<p>Daily rent</p>
							<span style="color: #FF0000;">{{discount_percent}} off</span>
						</li>
					</ul>
				</view>
				<p class="house_text">{{$t('house.detail.text1')}}{{house.canceldays||'0'}}{{$t('house.detail.text2')}}</p>
			</view>
			<view class="section-title">{{ $t('house.owner') }}</view>
			<view class="house-agent agent shadow flex-layout-col" @click.stop="handleChat">
				<image :src="agent.personalPhotoUrl?agent.personalPhotoUrl:'@/static/avatar.png'" mode="aspectFill">
				</image>
				<view class="house-agent-name h2 gap-col-top2">{{ agent.name }}</view>
				<view class="house-agent-tool"></view>
			</view>
			<view class="section-title gap-col-top2" v-if="house.remark">{{ $t('detail.description') }}</view>
			<view class="house-agent shadow gap-col2" v-if="house.remark">
				<text style="line-height: 1.5; font-size: 14px">{{ house.remark }}</text>
			</view>
			<view class="">
				<evalVue :eval="evalList"></evalVue>
				<u-loadmore v-if="hasMore" :status="loadStatus" />
			</view>
			<view v-show="systemConfig.payTips" class="section-title gap-col-top2">{{ $t('detail.tips') }}</view>
			<view v-show="systemConfig.payTips" class="house-agent shadow gap-col2">
				<text style="line-height: 1.5; font-size: 14px">{{ systemConfig.payTips }}</text>
			</view>
		</view>
		<view class="house-tool">
			<contact showText :phone="agent.phone" :houseid="id" :detail="house" :type="type" :start_time="start_time" :end_time="end_time"></contact>
		</view>
		<u-action-sheet @select="selectClick" @close="show = false" :actions="action" :closeOnClickOverlay="true"
			:closeOnClickAction="true" :cancelText="$t('text.cancel')" :show="show"></u-action-sheet>
		<u-calendar ref="calendar" :show="isCalendar" title="Date selection" startText="Check-in" endText="Check Out"
			:confirmText="$t('submit.submitButton')" :formatter="formatter" mode="range" @close="onCloseCalendar"
			@confirm="handleCalendar"></u-calendar>

	</view>
</template>

<script>
	import {
		mapGetters
	} from 'vuex';
	import {
		goBack,
		showAlert,
		showMessage,
		showFailure
	} from '../../lib/helper';
	import {
		check,
		getHouseDetail,
		getReviewList,
		reserveDateInfo,
		estimateRentPrice
	} from '../../lib/service';
	import demoPath from '@/static/demo/demo3.webp';
	import evalVue from '../../components/eval/eval.vue';
	import {
		getTodayDate,
		getNextMonthDate
	} from "@/utils/utils"
	export default {
		data() {
			return {
				show: false,
				path: '',
				id: '',
				swipeHeight: 387,
				house: {},
				agent: {},
				typeList: [],
				evalList: [],
				pageNo: 1,
				pageSize: 10,
				loadStatus: 'loadmore',
				hasMore: false,
				type: "",
				isCalendar: false,
				start_time: "",
				end_time: "",
				nights: 0,
				list: [],
				actual_money:"",
				cleanfee:"",
				discount_percent:"",
				discount_type:"",
				origin_money:"",
				commision_money:"",//佣金
				action: [{
						name: this.$t('check.action.check'),
						value: 1
					},
					{
						name: 'History',
						value: 2
					}
				]
			};
		},
		onLoad(options) {
			var id = options.id;
			this.id = id;
			this.type = options.type;
			var path = options.path;
			this.path = path;
		},
		onShow() {
			this.loadStatus = 'loadmore';
			this.hasMore = false;
			this.evalList = [];
			this.pageNo = 1;
			this.getData(this.id);
			this.loadData()
		},
		components: {
			evalVue
		},
		computed: {
			...mapGetters(['systemConfig'])
		},
		onPullDownRefresh() {
			this.pageNo = 1;
			this.evalList = [];
			this.loadData(true);
			uni.stopPullDownRefresh();
		},
		onReachBottom() {
			if (this.hasMore) {
				this.pageNo = this.pageNo + 1;
				this.loadData();
			}
		},
		methods: {

			handleAction() {
				if (!this.$store.state.user) {
					uni.navigateTo({
						url: '/pages/login/login'
					});
					return;
				}
				this.show = true;
			},
			getStatusBarHeight() {
				const phoneInfo = uni.getSystemInfoSync();

				return phoneInfo.statusBarHeight || 20;
			},
			getData(id) {
				getHouseDetail(id).then((res) => {
					this.house = res.data;
					this.agent = res.data.agency;
					if (this.house.type) {
						this.typeList = String(this.house.type).split('')
						console.log(this.typeList)
					}

				});
			},
			loadData(isReset) {
				this.loadStatus = 'loading';
				let obj = {
					pageNo: this.pageNo,
					pageSize: this.pageSize,
					houseid: this.id
				}
				getReviewList(obj).then((res) => {
						uni.hideLoading();
						this.loadStatus = 'no-more';
						this.hasMore = res.data.hasMore;
						if (isReset) {
							this.evalList = res.data.records;
						} else {
							this.evalList = this.evalList.concat(res.data.records);
						}
					})
					.catch((res) => {
						this.loadStatus = 'no-more';
						uni.hideLoading();
						showFailure();
					});
			},

			handleBack() {
				goBack();
			},
			handleChat() {
				uni.navigateTo({
					url: "/pages/new/chat?userid=" + this.agent.id + '&receiverid=' + this.agent.id
				})
			},
			handleCalendar(e) {
				let _this = this;
				this.start_time = e[0];
				this.end_time = e[e.length - 1];

				// this.nights = this.getNightsCount(this.start_time, this.end_time);
				let obj = {
					houseid: this.id,
					sdate: this.start_time,
					edate: this.end_time
				}
				estimateRentPrice(obj).then((res) => {
					if(res.statusCode==0){
						_this.nights = res.data.days;
						_this.commision_money = res.data.commision_money;
						_this.actual_money = res.data.actual_money;
						_this.cleanfee = res.data.cleanfee;
						_this.discount_percent = res.data.discount_percent;
						_this.discount_type = res.data.discount_type;
						_this.origin_money = res.data.origin_money;
						_this.isCalendar = false;
					}
				
				});
			},
			onCloseCalendar() {
				this.isCalendar = false;
			},
			onCalendar() {
				let _this = this;
				let start_time = getTodayDate();
				let end_time = getNextMonthDate();

				let obj = {
					houseid: this.id,
					sdate: start_time,
					edate: end_time
				}
				reserveDateInfo(obj).then((res) => {
					let list = res.data.list || [];
					_this.list = list;
					this.$nextTick(() => {
						_this.$refs.calendar.setFormatter(_this.formatter)
					})
					_this.isCalendar = true;

				});

			},
			formatDate(date) {
			  const year = date.getFullYear();
			  const month = (date.getMonth() + 1).toString().padStart(2, '0');
			  const day = date.getDate().toString().padStart(2, '0');
			  return `${year}-${month}-${day}`;
			},
			// 需要将对应的文案渲染到日历上
			formatter(day) {
				const date = new Date(day.date);
				const formattedDate = this.formatDate(date);
				this.list.forEach(bookedDate => {
					console.log('111', date == bookedDate.date && bookedDate.canreserve)
					if (formattedDate == bookedDate.date && bookedDate.canreserve) {
						day.bottomInfo = 'available'
						day.dot = false;
						day.disabled = false;
					}
					if (formattedDate == bookedDate.date && !bookedDate.canreserve) {
						day.bottomInfo = 'already booked'
						day.dot = false;
						day.disabled = true;
					}
				});
				return day
			},
			getNightsCount(startDate, endDate) {
				const oneDay = 24 * 60 * 60 * 1000; // 每天的毫秒数
				const startTime = new Date(startDate).getTime(); // 将日期转换为毫秒数
				const endTime = new Date(endDate).getTime(); // 将日期转换为毫秒数
				return Math.round((endTime - startTime) / oneDay); // 计算并返回夜数
			},
			handleCancel() {
				this.handleBack();
			},
			handleCheckIn() {
				uni.showToast({
					title: 'Success'
				});
			},
			selectClick(item) {
				console.log(item);
				if (item.value == 1) {
					uni.navigateTo({
						url: '/pages/detail/check/check?id=' + this.id
					});
				} else if (item.value == 2) {
					uni.navigateTo({
						url: '/pages/detail/check/list?id=' + this.id
					});
				}
			}
		}
	};
</script>

<style lang="scss" scoped>
	.house_text{
		font-size: 24rpx;
		margin-top: 10rpx;
	}
	.tags {
		padding: 4rpx 8rpx;
		border-radius: 6rpx;
		font-size: 28rpx;
		color: #7e99be;
		background: #e5f0ff;
	}

	.agent {
		image {
			width: 170rpx;
			height: 170rpx;
			background: #eeeeee;
			border-radius: 50%;
		}
	}

	.house_time {
		background: #FFFFFF;
		box-shadow: 0rpx 0rpx 10rpx 0rpx rgba(47, 60, 111, 0.06);
		border-radius: 20rpx;
		padding: 40rpx 30rpx;
		margin-bottom: 36rpx;

		.time_top {
			display: flex;
			align-items: center;
			justify-content: space-between;

			.time_text {
				p {
					font-family: Microsoft YaHei UI;
					font-weight: 400;
					font-size: 28rpx;
					color: #333333;
				}

				span {
					display: block;
					font-family: Microsoft YaHei UI;
					font-weight: 400;
					font-size: 24rpx;
					color: #999999;
					line-height: 13rpx;
					margin-top: 16rpx;
				}
			}

			.time_night {
				width: 130rpx;
				height: 40rpx;
				background: #FFFFFF;
				border-radius: 20rpx;
				border: 2rpx solid #036EFC;
				text-align: center;
				line-height: 40rpx;
				font-family: Microsoft YaHei UI;
				font-weight: 400;
				font-size: 22rpx;
				color: #333333;
			}
		}

		.time_bottom {
			margin-top: 38rpx;

			ul {
				display: flex;
				align-items: center;
				justify-content: space-between;

				li {
					width: 40%;
					text-align: center;

					image {
						width: 50rpx;
						height: 34rpx;
					}

					p {
						font-family: Microsoft YaHei UI;
						font-weight: 400;
						font-size: 20rpx;
						color: #333333;
					}

					span {
						font-family: Microsoft YaHei UI;
						font-weight: 400;
						font-size: 22rpx;
						color: #999999;
					}
				}
			}
		}
	}

	.house-navbar {
		position: fixed;
		left: 10px;
		right: 10px;
		top: 10px;
		height: 60px;
		z-index: 9999;

		&-tool {
			display: flex;
			align-items: center;
			justify-content: space-between;
		}
	}

	.property-card {
		flex: 1;
		height: 70px;
		display: flex;
		margin: 0 8px;
		flex-flow: column;
		justify-content: center;
		align-items: center;
		border-radius: 12px;
		color: $app-color-primary;
		background-color: #fff;

		&-value {
			margin-top: 2px;
		}

		text {
			font-size: 14px;
		}
	}

	.house {
		padding-bottom: 68px;
		background-color: #f9fbff;

		&-images {
			margin-bottom: 8px;
		}

		&-content {
			padding: 10px 30px;
		}

		&-property {
			margin-top: 20px;
			margin-bottom: 20px;
			display: flex;
			justify-content: space-around;
		}

		&-agent {
			align-items: center;
			background-color: #fff;
			padding: 20px 10px;
			border-radius: 12px;

			&-name {
				margin: 10px 0;
			}

			&-tool {
				display: inline-grid;
				grid-template-columns: 1fr 1fr 1fr;
			}
		}

		&-tool {
			background-color: #fff;
			position: fixed;
			padding: 10px;

			bottom: 0;
			left: 0;
			right: 0;
		}
	}

	.info-card {
		border-radius: 8px;
		background-color: #fff;
		margin: 8px 8px;
		padding: 10px 20px;

		&-title {}

		&-content {
			padding: 16px 0;
		}

		.user-card {
			align-items: center;

			&-name {
				margin: 10px;
			}
		}
	}
</style>